<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"/>
    <!-- Link Swiper's CSS -->
    <link rel="stylesheet" href="./lib/swiper-bundle.min.css"/>

    <title>豆瓣App-市集</title>
    <link rel="shortcut icon" href="https://img3.doubanio.com/favicon.ico">
    <link rel="stylesheet" href="./css/reset.css">
    <link rel="stylesheet" href="./img/icon/font_iconfont/iconfont.css">
    <link rel="stylesheet" href="./css/app-public.css">
    <link rel="stylesheet" href="./css/app-market.css">
</head>
<body>
    <div class="mobile">
        <header>
            <div class="functional_domain flexBox">
                <span class="showMore iconfont">&#xe66d;</span>
                <div class="searchBar flexBox">
                    <span class="iconfont">&#xe8d6;</span>
                    <span class="placeholder">抹香香是一件令人幸福的小事</span>
                </div>
                <span class="showMessage iconfont">&#xe65e;</span>
            </div>
        </header>
        
        <aside>
            <div class="main">
                <div class="hd flexBox">
                    <span class="iconfont close">&#xe600;</span>
                    <span class="iconfont">&#xe60e;</span>
                </div>
                <div class="mid">
                    <div class="user flexBox">
                        <div class="avatar"><img src="./img/avatar.jpg" alt=""></div>
                        <span class="username">未登录</span>
                    </div>
                    <div class="userFuncArea">
                        <div class="top">
                            <div class="item flexBox">
                                <span class="iconfont">&#xe70f;</span>
                                <span class="text">我的收藏/豆列</span>
                                <span class="rightText">我的豆列在这里</span>
                            </div>
                            <div class="item flexBox">
                                <span class="iconfont">&#xe609;</span>
                                <span class="text">我的关注</span>
                            </div>
                            <div class="item flexBox">
                                <span class="iconfont">&#xe638;</span>
                                <span class="text">我的浏览</span>
                            </div>
                        </div>
                        <div class="bottom">
                            <div class="item flexBox">
                                <span class="iconfont">&#xe621;</span>
                                <span class="text">青少年模式</span>
                            </div>
                            <div class="item flexBox">
                                <span class="iconfont">&#xe621;</span>
                                <span class="text">设置</span>
                            </div>
                            <div class="item flexBox">
                                <span class="iconfont">&#xe624;</span>
                                <span class="text">帮助与反馈</span>
                            </div>
                            <div class="item flexBox">
                                <span class="iconfont">&#xf706;</span>
                                <span class="text">社区管理中心</span>
                            </div>
                            <div class="item flexBox logOut">
                                <span class="iconfont">&#xe621;</span>
                                <span class="text">退出登录</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="bd">
                    <div class="topFuncArea flexBox">
                        <div class="item flexBox">
                            <span class="iconfont order"></span>
                            <span class="text">订单</span>
                        </div>
                        <div class="item flexBox">
                            <span class="iconfont cart"></span>
                            <span class="text">购物车(2)</span>
                        </div>
                        <div class="item flexBox">
                            <span class="iconfont wallet"></span>
                            <span class="text">钱包</span>
                        </div>
                        <div class="item flexBox">
                            <span class="iconfont db_time"></span>
                            <span class="text">豆瓣时间</span>
                        </div>
                        <div class="item flexBox">
                            <span class="iconfont db_bookshelf"></span>
                            <span class="text">豆瓣阅读书架</span>
                        </div>
                    </div>
                    <div class="license">
                        <img src="./img/副页-license.png" alt="">
                        <span>证照信息<span class="iconfont">&#xe6a3;</span></span>
                    </div>
                </div>
            </div>
            <div class="mask"></div>
        </aside>

        <main>
            <!-- 其他产品 -->
            <section class="otherProduct flexBox">
                <a href="javascript:void(0)" class="product_item">
                    <span class="logo"><img src="./img/app-market/douban-doupin.jpg" alt="豆瓣豆品"></span>
                    <span class="name">豆瓣豆品</span>
                </a>
                <a href="javascript:void(0)" class="product_item">
                    <span class="logo"><img src="./img/app-market/douban-time.jpg" alt="豆瓣时间"></span>
                    <span class="name">豆瓣时间</span>
                </a>
                <a href="javascript:void(0)" class="product_item">
                    <span class="logo"><img src="./img/app-market/douban-bookstore.jpg" alt="豆瓣书店"></span>
                    <span class="name">豆瓣书店</span>
                </a>
            </section>

            <!-- 海报轮播图 -->
            <section class="posterCarousel">
                <div class="swiper carouselSwiper">
                    <div class="swiper-wrapper">
                        <div class="swiper-slide">
                            <a href="javascript:void(0);"><img src="./img/app-market/posterCarousel-1.jpg" alt=""></a>
                        </div>
                        <div class="swiper-slide">
                            <a href="javascript:void(0);"><img src="./img/app-market/posterCarousel-2.jpg" alt=""></a>
                        </div>
                        <div class="swiper-slide">
                            <a href="javascript:void(0);"><img src="./img/app-market/posterCarousel-3.jpg" alt=""></a>
                        </div>
                    </div>
                    <div class="swiper-pagination dot"></div>
                </div>
            </section>

            <!-- 主要类别 -->
            <section class="categories flexBox">
                <a href="javascript:void(0);" class="category_item flexBox">
                    <img src="./img/app-market/categorie_item-1.jpg" alt="舒服居家">
                    <span class="name">舒服居家</span>
                </a>
                <a href="javascript:void(0);" class="category_item flexBox">
                    <img src="./img/app-market/categorie_item-2.jpg" alt="宝藏零食">
                    <span class="name">宝藏零食</span>
                </a>
                <a href="javascript:void(0);" class="category_item flexBox">
                    <img src="./img/app-market/categorie_item-3.jpg" alt="微醺酒馆">
                    <span class="name">微醺酒馆</span>
                </a>
                <a href="javascript:void(0);" class="category_item flexBox">
                    <img src="./img/app-market/categorie_item-4.jpg" alt="三餐四季">
                    <span class="name">三餐四季</span>
                </a>
                <a href="javascript:void(0);" class="category_item flexBox">
                    <img src="./img/app-market/categorie_item-5.jpg" alt="美丽出行">
                    <span class="name">美丽出行</span>
                </a>
            </section>

            <!-- 团购 & 推荐 -->
            <section class="recommendArea flexBox">
                <div class="group_purchase recommend_item">
                    <div class="head flexBox">
                        <span class="title">豆小铺团购</span>
                        <span class="time">周二/四开团</span>
                        <span class="iconfont">&#xe6a3;</span>
                    </div>
                    <div class="content">
                        <div class="swiper mySwiper2">
                            <div class="swiper-wrapper">
                                <div class="swiper-slide">
                                    <div class="img"><img src="./img/app-market/mySwiper2-1.jpg" alt=""></div>
                                    <div class="main flexBox">
                                        <span class="tag">限时团购·5天优惠</span>
                                        <span class="name">苏州纸皮烧麦</span>
                                        <span class="decription">皮比纸薄，个头超大！</span>
                                    </div>
                                </div>
                                <div class="swiper-slide">
                                    <div class="img"><img src="./img/app-market/mySwiper2-2.jpg" alt=""></div>
                                    <div class="main flexBox">
                                        <span class="tag">限时团购·5天优惠</span>
                                        <span class="name">台湾在地系列花草茶</span>
                                        <span class="decription">这个身心都滋润的秋冬</span>
                                    </div>
                                </div>
                                <div class="swiper-slide">
                                    <div class="img"><img src="./img/app-market/mySwiper2-3.jpg" alt=""></div>
                                    <div class="main flexBox">
                                        <span class="tag">限时团购·5天优惠</span>
                                        <span class="name">密森·海盐侧柏洗发露</span>
                                        <span class="decription">让头皮像森林般自在呼吸</span>
                                    </div>
                                </div>
                                <div class="swiper-slide">
                                    <div class="img"><img src="./img/app-market/mySwiper2-4.jpg" alt=""></div>
                                    <div class="main flexBox">
                                        <span class="tag">限时团购·5天优惠</span>
                                        <span class="name">密森·海盐侧柏头皮净化膏</span>
                                        <span class="decription">让头皮像森林般自在呼吸</span>
                                    </div>
                                </div>
                            </div>
                          </div>
                    </div>
                </div>
                <div class="weekly_recommend recommend_item">
                    <div class="head flexBox">
                        <span class="title">本周推荐</span>
                        <span class="time">每周五更新</span>
                        <span class="iconfont">&#xe6a3;</span>
                    </div>
                    <div class="content flexBox">
                        <div class="wares_item_s">
                            <div class="img"><img src="./img/app-market//weekly_recommend-1.jpg" alt="豆瓣读书周历2023·诗歌"></div>
                            <span class="name">豆瓣读书周历2023·诗歌</span>
                            <div class="price">
                                <span class="new"><span>¥</span>88</span>
                            </div>
                        </div>
                        <div class="wares_item_s">
                            <div class="img"><img src="./img/app-market//weekly_recommend-2.jpg" alt="豆瓣电影日历2023 经典版"></div>
                            <span class="name">豆瓣电影日历2023 经典版</span>
                            <div class="price">
                                <span class="new"><span>¥</span>99</span>
                            </div>
                        </div>
                        <div class="wares_item_s">
                            <div class="img"><img src="./img/app-market//weekly_recommend-3.jpg" alt="贝灵哲白仙粉黛桃红葡萄酒"></div>
                            <span class="name">贝灵哲白仙粉黛桃红葡萄酒</span>
                            <div class="price">
                                <span class="new"><span>¥</span>118</span>
                            </div>
                        </div>
                        <div class="wares_item_s">
                            <div class="img"><img src="./img/app-market//weekly_recommend-4.jpg" alt="阿黑阿白猫猫头抱枕"></div>
                            <span class="name">阿黑阿白猫猫头抱枕</span>
                            <div class="price">
                                <span class="new"><span>¥</span>68</span>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- 豆瓣豆品 -->
            <section class="douPin">
                <span class="tag">豆瓣豆品</span>
                <div class="poster"><img src="./img/app-market/poster-doupin.jpg" alt="豆瓣电影日历2023 经典版"></div>
                <div class="main">
                    <div class="head flexBox">
                        <span class="name">豆瓣电影日历2023 经典版</span>
                        <span class="buy_now_btn">
                            立即购买<span class="iconfont">&#xe6a3;</span>
                        </span>
                    </div>
                    <div class="subhead">每一天，都是与众不同的一天</div>
                    <div class="wares_area flexBox">
                        <div class="wares_item_s">
                            <div class="img"><img src="./img/app-market/doupin-1.jpg" alt="豆瓣读书周历2023·诗歌"></div>
                            <span class="name">豆瓣读书周历2023·诗歌</span>
                            <div class="price">
                                <span class="new"><span>¥</span>88</span>
                            </div>
                        </div>
                        <div class="wares_item_s">
                            <div class="img"><img src="./img/app-market/doupin-2.jpg" alt="豆瓣金属中性笔"></div>
                            <span class="name">豆瓣金属中性笔</span>
                            <div class="price">
                                <span class="new"><span>¥</span>39</span>
                            </div>
                        </div>
                        <div class="wares_item_s">
                            <div class="img"><img src="./img/app-market/doupin-3.jpg" alt="豆瓣艺术帽衫"></div>
                            <span class="name">豆瓣艺术帽衫</span>
                            <div class="price">
                                <span class="new"><span>¥</span>139</span>
                                <span class="old"><span>¥</span>158</span>
                            </div>
                        </div>
                        <div class="wares_item_s">
                            <div class="img"><img src="./img/app-market/doupin-4.jpg" alt="豆瓣收藏夹"></div>
                            <span class="name">豆瓣收藏夹</span>
                            <div class="price">
                                <span class="new"><span>¥</span>99</span>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- 秋日酒单 -->
            <section class="autumnWineList">
                <span class="tag">秋日酒单</span>
                <div class="poster"><img src="./img/app-market/poster-AutumnWineList.jpg" alt="秋日微醺酒单第二弹——葡萄酒专场"></div>
                <div class="main">
                    <div class="head flexBox">
                        <span class="name">秋日微醺酒单第二弹——葡萄酒专场</span>
                        <span class="buy_now_btn">
                            去逛逛
                            <span class="iconfont">&#xe6a3;</span>
                        </span>
                    </div>
                    <div class="subhead">秋日小酌、假期聚会、回家送礼都超合适~</div>
                    <div class="wares_area flexBox">
                        <div class="wares_item_s">
                            <div class="img"><img src="./img/app-market/AutumnWineList-1.png" alt="卡浦皇长相思干白葡萄酒"></div>
                            <span class="name">卡浦皇长相思干白葡萄酒</span>
                            <div class="price">
                                <span class="new"><span>¥</span>128</span>
                            </div>
                        </div>
                        <div class="wares_item_s">
                            <div class="img"><img src="./img/app-market/AutumnWineList-2.png" alt="葛兰苏霞多丽白葡萄酒"></div>
                            <span class="name">葛兰苏霞多丽白葡萄酒</span>
                            <div class="price">
                                <span class="new"><span>¥</span>88</span>
                            </div>
                        </div>
                        <div class="wares_item_s">
                            <div class="img"><img src="./img/app-market/AutumnWineList-3.png" alt="洛斯卡托桃红低泡葡萄酒"></div>
                            <span class="name">洛斯卡托桃红低泡葡萄酒</span>
                            <div class="price">
                                <span class="new"><span>¥</span>98</span>
                            </div>
                        </div>
                        <div class="wares_item_s">
                            <div class="img"><img src="./img/app-market/AutumnWineList-4.png" alt="卡浦皇干红葡萄酒"></div>
                            <span class="name">卡浦皇干红葡萄酒</span>
                            <div class="price">
                                <span class="new"><span>¥</span>128</span>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- 豆小铺零食小仓库 -->
            <section class="douShop-poster">
                <img src="./img/app-market/dou-shop.png" alt="豆小铺零食小仓库">
            </section>

            <!-- 豆小铺零食商品 -->
            <section class="douShopSnacks">
                <div class="wares_area flexBox">
                    <div class="wares_area_left"></div>
                    <div class="wares_area_right"></div>
                </div>
            </section>

            <!-- 全部好货 -->
            <div class="allCommodities">
                <div class="head">全部好物</div>
                <div class="tagArea">
                    <div class="type_tags">
                        <div class="container">
                            <span class="tag current" data-type="all">全部</span>
                            <span class="tag" data-type="snacks">宝藏零食</span>
                            <span class="tag" data-type="alcohol">微醺酒馆</span>
                            <span class="tag" data-type="meal">三餐四季</span>
                            <span class="tag" data-type="household">舒服居家</span>
                            <span class="tag" data-type="travel">美丽出行</span>
                        </div>
                    </div>
                </div>
                <div class="wares_area flexBox">
                    <div class="wares_area_left"></div>
                    <div class="wares_area_right"></div>
                </div>
            </div>

            <!-- 选择商品的参数 -->
            <div class="productSelectionDetail">
                <!-- 遮罩 -->
                <div class="mask"></div>
                <div class="tipsArea">
                    <div class="loginFirst">请先登录豆瓣账号</div>
                    <div class="addCartSuccess">成功加入购物车</div>
                </div>
            </div>
        </main>

        
        <footer>
            <div class="container flexBox">
                <a href="./index.html" class="item flexBox" id="index" data-index="1">
                    <span class="iconfont" data-index="1"></span>
                    <span class="text" data-index="1">首页</span>
                </a>
                <a href="./app-movie.html" class="item flexBox" id="media" data-index="2">
                    <span class="iconfont" data-index="2"></span>
                    <span class="text" data-index="2">书影音</span>
                </a>
                <a href="./app-group.html" class="item flexBox" id="group" data-index="3">
                    <span class="iconfont" data-index="3"></span>
                    <span class="text" data-index="3">小组</span>
                </a>
                <a href="javascript:void(0);" class="item flexBox current" id="market" data-index="4">
                    <span class="iconfont" data-index="4"></span>
                    <span class="text" data-index="4">市集</span>
                </a>
                <a href="./app-user.html" class="item flexBox" id="user" data-index="5">
                    <span class="iconfont" data-index="5"></span>
                    <span class="text" data-index="5">我</span>
                </a>
            </div>
            
            <a href="javascript:void(0);" class="go_to_cart_page"></a>
        </footer>
    </div>
    <canvas id="myCanvas" style="display: none;"></canvas> 
</body>
<script src="./lib/jquery-3.6.1.min.js"></script>
<script src="./lib/swiper-bundle.min.js"></script>
<script src="./lib/EasyLazyload.min.js"></script>
<script src="./lib/jquery.bcakgroundColor.js"></script> <!-- 背景颜色渐变插件 -->
<script src="./js/app-public.js"></script>

<!-- Initialize Swiper -->
<script>
    var swiper = new Swiper(".carouselSwiper", {
        slidesPerView: 1,
        spaceBetween: 15,
        loop: true,
        speed:300,
        autoplay:true,
        autoplay:{
            delay: 5000,
            disableOnInteraction : false
        },
        pagination: {
            el: ".swiper-pagination",
            clickable: true,
        },
        navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
        },
    });

    var swiper2 = new Swiper(".mySwiper2", {
        grabCursor: true,
        effect: "creative",
        creativeEffect: {
          prev: {
            // shadow: true,
            translate: ["-100%", 0, 0],
          },
          next: {
            // shadow: true,
            translate: ["6%", 0, -100],
          },
        },
        loop: true,
        speed:300,
        autoplay:true,
        autoplay:{
            delay: 5000,
            disableOnInteraction : false
        },
      });
</script>

<script>
    $(function(){
        var type = 'all';  // “全部好货” 的小标签tag 类型 初始化
        
        // 数据渲染
        // 豆小铺零食 商品  发送请求
        $.ajax({
            type:'get',
            data:{type:'snacks'},
            async:false,
            url:'/getDouShopProductData',
            success:function(res){
                console.log('获取'+type+'类型商品信息',res);
                
                // 数据渲染
                dataRender('.douShopSnacks',res);
            },
            error:function(err){
                console.log('err',err);
            }
        })

        // 全部好货列表   发送请求
        getTypeProductData('all','');


        // 轮播图获取图片颜色值
        var canvas = document.querySelector('#myCanvas');
        var slides = document.querySelectorAll('.group_purchase .swiper-slide');
        slides.forEach((item)=>{
            var img = $(item).find('img')[0];
            var rgbObj = getImageColor(img,canvas);               // 调用方法 获取rgb值
            if(img.complete){
                console.log('当前有缓存')
            }
            else{
                console.log('当前无缓存，需要重新加载一下');
                img.onload = function(){
                    console.log('img加载成功')
                    var rgbObj = getImageColor(img,canvas);               // 调用方法 获取rgb值
            
                    var r = parseInt(rgbObj.r);
                    var g = parseInt(rgbObj.g);
                    var b = parseInt(rgbObj.b);
                    var bgImg = `linear-gradient(rgba(255,255,255,0)0%,rgb(${r},${g},${b})100%)`;
                    $(item).find('.main').css('background-image',bgImg);
                }
            }
        })

        // 全部好货 的 tag点击事件
        $('.allCommodities .type_tags').on('click',function(e){
            let type = e.target.dataset.type;

            // 样式切换
            $(e.target).addClass('current').siblings().removeClass('current');


            // 发送请求
            getTypeProductData(type,10);
        })


        // 商品tag 滚动到顶部时，固定定位
        var elTop = $('.allCommodities .type_tags').offset().top;  // 元素距离顶部距离
        $(window).scroll(function(){
            var winSrc = $(window).scrollTop();
            
            if(elTop - winSrc <= 50){
                $('.allCommodities .type_tags').addClass('fixed');
            }
            else{
                $('.allCommodities .type_tags').removeClass('fixed');
            }
        })
    
        // 红色购物车小图标点击事件
        addToCart('.allCommodities');
        addToCart('.douShopSnacks');

    })

    
    // 全部好货列表   发送请求
    // 参数1：商品类型
    // 参数2：响应商品数据条数
    function getTypeProductData(type,num){
        $.ajax({
            type:'get',
            data:{type:type,num:num},
            async:false,
            url:'/getProductData',
            success:function(res){
                console.log('获取'+type+'类型商品信息',res);

                // 数据渲染
                dataRender('.allCommodities',res);

                // 无限滚动
                addMore(res);
            },
            error:function(err){
                console.log('err',err);
            }
        })
    }


    // 页面初始化 进行数据渲染
    // 参数1：元素样式类名(要对谁进行数据渲染)  
    // 参数2：商品所有数据的数组
    function dataRender(obj,res){
        var wares_area_left = '',wares_area_right = '';
        res.forEach((item,index)=>{

            var productId = item.productId,             // 商品id
                name = item.name,                       // 商品名称
                description = item.description,         // 商品描述
                discount = item.discount,               // 优惠
                looking = item.looking,                 // 在逛人数
                newPrice = item.newPrice,               // 现在的价格
                oldPrice = item.oldPrice,               // 以前的价格
                unit = item.unit,                       // 单位
                posterSrc = item.posterSrc,             // 图片路径
                isTimeLimit = item.isTimeLimit,         // 是否是 '限时'
                isGroupBuying = item.isGroupBuying;     // 是否是 '正在开团'
            
            // 是否有优惠tag
            var discount_tag = '';
            if(discount.length > 0){
                discount.forEach((item)=>{
                    discount_tag += `<span class="discount_tag">${item}</span>`;
                })
            }
            // 是否是 限时
            var time_limit = '';
            if(isTimeLimit){
                time_limit = '<span class="time_limit">限时</span>';
            }
            // 是否有单位
            var unit_span = '';
            if(unit !== ''){
                unit_span = `<span class="unit">/${unit}</span>`;
            }
            // 是否有旧价格
            var oldPrice_span = '';
            if(oldPrice !== ''){
                oldPrice_span = `<span class="old"><span>¥</span>${oldPrice}</span>`;
            }
            // 是否是正在开团
            var group_buying_con = '';
            if(isGroupBuying){
                group_buying_con = `<div class="group_buying">
                                        <span>
                                            正在开团<span class="iconfont">&#xe6a3;</span>
                                        </span>
                                    </div>`;
            }

            var wares_item_l = `<div class="wares_item_l" data-productId="${productId}">
                                    <div class="img"><img data-lazy-src="${posterSrc}" alt="${name}"></div>
                                    <div class="title">
                                        <span class="snacks iconfont"><img src="./img/app-market/snacks_icon.jpg" alt="小图标"></span>
                                        <span class="description">${description}</span>
                                    </div>
                                    <div class="looking_more flexBox">
                                        ${discount_tag}
                                        <span class="looking">${looking}人再逛</span>
                                    </div>
                                    <div class="price_addCart flexBox">
                                        <span class="price">
                                            <span class="new">
                                                ${time_limit}
                                                ¥
                                                <span class="num">${newPrice}</span>
                                                ${unit_span}
                                            </span>
                                            ${oldPrice_span}
                                        </span>
                                        <span class="add_cart_btn iconfont" data-id="${productId}"></span>
                                    </div>
                                    ${group_buying_con}
                                </div>`;

            if(index % 2 == 0){
                wares_area_left += wares_item_l;
            }
            else{
                wares_area_right += wares_item_l;
            }

        })
        $(obj+' .wares_area .wares_area_left').html(wares_area_left);
        $(obj+' .wares_area .wares_area_right').html(wares_area_right);
        // 懒加载
        lazyLoadAgain();
    }
    
    // 无限滚动  只有"全部好货"模块有无限滚动，指定了最大长度25
    // 参数1：相应参数的数组
    function addMore(res){
        $(window).scroll(function(){
            var mainHei = $('main').height();
            var winHei = $(window).height();
            var winScr = $(window).scrollTop();

            var wares_item_Num = $('.allCommodities .wares_area .wares_area_left .wares_item_l').length;
            var wares_item_maxNum = 20;
            // 一个一个追加，最大长度为20
            if(wares_item_Num < wares_item_maxNum && winScr >= mainHei - winHei){
                // 获取新元素
                var type = $('.allCommodities span.current').attr('data-type');

                var appendArr = res;  // 新数组
                for(var i = 0; i<2; i++){
                    // 随机抽取
                    var random = Math.floor(Math.random() * (res.length-0)+0);
                    appendArr.push(res[random]);
                }
                // 数据渲染
                dataRender('.allCommodities',appendArr);
            }
        })
    }

    
    // 红色购物车小图标点击事件
    // 参数1：购物车小图片的最外层父级的类名
    function addToCart(obj){
        $(obj).on('click',function(e){
            var product_id = e.target.dataset.id;
            console.log(product_id);
            if(product_id){
                // 发送请求，进行数据渲染
                $.ajax({
                    type:'get',
                    data:{product_id},
                    async:false,
                    url:'/getProductDetail',
                    success:function(res){
                        console.log('获取指定id商品信息',res);
                        
                        let productId = res.productId,             // 商品id
                            name = res.name,                       // 商品名称
                            posterSrc = res.posterSrc,             // 图片路径
                            params = res.params;                   // 商品的参数

                        // 价格最大值   价格最小值      商品参数盒子    请选择 内容 提示内容
                        let minPrice = 0, maxPrice = 0, paramsBox = '',pleaseChooseTextBox='';
                        
                        // 找到价格 的 最大值/最小值
                        function minOrMax(num){
                            if(num <= minPrice) minPrice = parseFloat(num);
                            if(num >= maxPrice) maxPrice = parseFloat(num);
                        }

                        // 参数和参数值遍历
                        for(let i = 0; i<params.length; i++){
                            let paramId = params[i].paramId;  // 参数编号
                            let paramName = params[i].name;   // 参数名称
                            let paramValue = params[i].value;

                            // 请选择文本部分内容拼接
                            pleaseChooseTextBox += `<span>"${paramName}"</span>`;
                            
                            // 一个参数主要内容拼接
                            let oneParamBox = `<div class="${paramId} paramItem flexBox">
                                                    <span class="paramName">${paramName}:</span>
                                                    <div class="paramValue">`;

                            // 遍历 该参数 对应的参数值  进行拼接
                            for(let j = 0; j<paramValue.length; j++){
                                let valueId = paramValue[j].valueId;    // 参数值的id
                                let valueName = paramValue[j].data;     // 参数值的名字
                                let valuePriceObj = paramValue[j].price;   // 商品价格
                                let valueImgSrc= paramValue[j].imgSrc;  // 商品对应图片

                                // 最大值/最小值 初始化
                                minPrice = paramValue[0].price['p1v1'];
                                maxPrice = paramValue[0].price['p1v1'];
                                

                                // 遍历所有价格 调用方法 找到价格区间
                                $.each(valuePriceObj,function(key,value){
                                    minOrMax(parseFloat(value));       // 获取价格最大值和最小值
                                })

                                // 参数盒子 内容 的 拼接
                                oneParamBox += `<span class="${valueId}" data-value_index="${j+1}">${valueName}</span>`;
                            }
                            oneParamBox += `</div></div>`;
                            paramsBox += oneParamBox;
                        }

                        // 价格盒子   如果最大值等于最小值，则没有价格区间
                        var priceBox = '';
                        if(minPrice == maxPrice){
                            priceBox = `¥<span class="minPrice">${minPrice}</span>`;
                        }
                        else{
                            priceBox = `¥<span class="minPrice">${minPrice}</span> - ¥<span class="maxPrice">${maxPrice}</span>`;
                        }
                        
                        // 追加 商品选购模块 整个内容 到文档中
                        var productSelectionDetail = `<div class="main">
                                                        <div class="head flexBox">
                                                            <div class="poster"><img src="${posterSrc}" alt="${name}"></div>
                                                            <div class="info flexBox">
                                                                <span class="name">${name}</span>
                                                                <div class="price">
                                                                    ${priceBox}
                                                                </div>
                                                                <div class="paramTips">
                                                                    请选择 ${pleaseChooseTextBox}
                                                                </div>
                                                            </div>
                                                            <div class="closeArea">
                                                                <span class="iconfont closeBtn">&#xe600;</span>
                                                            </div>
                                                        </div>
                                                        <div class="paramChooseArea">
                                                            ${paramsBox}
                                                        </div>
                                                        <div class="quantity flexBox">
                                                            <span class="paramName">数量:</span>
                                                            <div class="plus_minus flexBox">
                                                                <span class="minus iconfont disabled">&#xeb79;</span>
                                                                <span class="number">1</span>
                                                                <span class="plus iconfont disabled">&#xeb78;</span>
                                                            </div>
                                                        </div>
                                                        <div class="operations flexBox">
                                                            <div class="add_to_cart">加入购物车</div>
                                                            <div class="buy_now">立即购买</div>
                                                        </div>
                                                    </div>`;
                        $('.productSelectionDetail').prepend(productSelectionDetail);

                        // 添加事件
                        productSelectionDetailEvents(productId,params);

                        // 显示 商品选购模块
                        $('.productSelectionDetail').fadeIn(500);
                    },
                    error:function(err){
                        console.log('err',err);
                    }
                })
            }
        })
    }


    // 商品选购模块 的相关事件
    // 参数1：商品参数的数组
    function productSelectionDetailEvents(productId,params){

        // 1. 点击关闭按钮/遮罩层，商品选购模块隐藏，移除内容
        $('.productSelectionDetail .closeBtn').on('click',function(){
            $('.productSelectionDetail').fadeOut(300);
            $('.productSelectionDetail .main').remove();
        })
        $('.productSelectionDetail .mask').on('click',function(){
            $('.productSelectionDetail').fadeOut(300);
            $('.productSelectionDetail .main').remove();
        })


        // 2. 商品参数的可选值 点击事件
        $('.paramItem .paramValue').on('click',function(e){
            console.log('触发一次');
            let valueIndex = e.target.dataset.value_index;
            if(valueIndex){
                // 修改样式
                $(e.target).toggleClass('selected').siblings().removeClass('selected');


                // 更新 选择信息文字内容
                // 如果 已选择的标签个数 != 商品的参数个数
                if($('.paramItem').find('span.selected').length != $('.paramItem').length){
                    console.log('还有参数没选择');
                    
                    // 请选择文本 拼接
                    let spanBox = '';
                    let spanArr = [];
                    // for(var i = 0; i<testArr3.length;i++){
                    //     if(newArr.indexOf(testArr3[i]) === -1){
                    //         newArr.push(testArr3[i]);
                    //     }
                    // }
                    $('.paramItem').each((index,item)=>{
                        if($(item).find('span.selected').length == 0){
                            console.log($(item).find('.paramName').html().replace(':',''));
                            let param_name = $(item).find('.paramName').html().replace(':','');
                            spanBox += `<span>"${param_name}"</span>`;
                        }
                    })
                    console.log(spanBox);
                    

                    // 修改选择信息文字内容为 请选择+标签
                    $('.paramTips').html(' 请选择 '+spanBox);

                    
                    // 数量-加号 禁用
                    $('.quantity .plus').addClass('disabled');
                }
                else{
                    console.log($('.paramItem').find('span.selected').length,'都选择了');

                    let selectedArr = $('.paramItem').find('span.selected');  // 已选择的标签的数组
                    let selectedLen = selectedArr.length;                     // 已选择的标签数组长度
                    // 第一个选择的标签的id
                    let item1_valueId = selectedArr.first().get(0).classList[0];
                    // 商品参数id
                    let item2_paramId = selectedArr.last().parents('.paramItem').get(0).classList[0]; 
                    // 商品参数的可选性id
                    let item2_valueId = selectedArr.last().get(0).classList[0];

                    // 修改选择信息文字内容为 已选择+标签
                    let spanBox = '';
                    for(var i = 0; i<selectedLen; i++){
                        spanBox += `<span class="${selectedArr[i].classList[0]}">"${selectedArr[i].innerHTML}"</span>`;
                    }
                    $('.paramTips').html(' 已选择 '+spanBox);


                    // 数量-加号 解除禁用
                    $('.quantity .plus').removeClass('disabled');



                    // 修改价格 修改图片

                    // 过滤出 符合条件的param value
                    let param_value = params.filter(function(item){
                        return item.paramId == item2_paramId;
                    })[0].value.filter(function(item){
                        return item.valueId == item2_valueId;
                    })[0];

                    let price = param_value.price[item1_valueId];   // 商品价格
                    let imgSrc = param_value.imgSrc;                // 商品图片

                    $('.productSelectionDetail .head .info .price').html('¥'+price);
                    $('.productSelectionDetail .head .poster img').attr('src',imgSrc);
                }
                
            }
        })


        // 3. 如果 商品只有一个参数，且该参数只有一个可选值，就默认选中
        if(params.length == 1 && params[0].value.length == 1){
            $('.paramItem .paramValue span').trigger('click');
        }


        // 4. 数量 加减按钮的事件
        $('.quantity .minus').on('click',function(e){
            if($(this).hasClass('disabled') == false){
                var number = $('.quantity .number').get(0).innerHTML;
                if(number > 1){
                    number--;
                    $('.quantity .number').get(0).innerHTML = number;
                }
                if(number == 1){
                    $(this).addClass('disabled');
                }
            }
        })
        $('.quantity .plus').on('click',function(e){
            if($(this).hasClass('disabled') == false){
                $('.quantity .number').get(0).innerHTML++;
                $('.quantity .minus').removeClass('disabled');
            }
        })
        

        // 5. 加入购物车功能
        $('.operations .add_to_cart').on('click',function(){
            // 验证当前是否有用户登录
            $.ajax({
                type:'post',
                async:false,
                url:'/postUserSession',
                success:function(res){
                    console.log('res',res);
                    if(res.status == false){
                        $('.productSelectionDetail .tipsArea').show();
                        $('.productSelectionDetail .tipsArea .loginFirst').show();
                        setTimeout(() => {
                            $('.productSelectionDetail .tipsArea .loginFirst').hide();
                            $('.productSelectionDetail .tipsArea').hide();
                            window.location.href = 'http://localhost:3000/login/login.html';
                        }, 1500);
                    }
                    else{
                        // 如果 商品参数都选择了
                        if($('.paramItem').find('span.selected').length == $('.paramItem').length){
                            console.log('addCart 都选择了');
                            
                            console.log(productId);
                            var productCartId = productId;
                            var product_name = $('.productSelectionDetail .head .info .name').html();
                            var product_price = $('.productSelectionDetail .head .info .price').html().replace('¥','');
                            var param_value_arr = [];
                            $('.productSelectionDetail .head .info .paramTips span').each((index,item)=>{
                                productCartId += `_${item.classList[0]}`; 
                                param_value_arr.push(item.innerHTML);
                            })
                            var product_quantity = $('.productSelectionDetail .quantity .number').html();
                            var product_imgSrc = $('.productSelectionDetail .head .poster img').attr('src');

                            
                            var productItem = {
                                productCartId:productCartId,
                                name:product_name,
                                price:product_price,
                                params:param_value_arr,
                                quantity:product_quantity,
                                imgSrc:product_imgSrc
                            };

                            console.log(productItem);

                            $.ajax({
                                type:'post',
                                data:productItem,
                                async:false,
                                url:'/postProductToMyCart',
                                success:function(res){
                                    console.log('res',res);
                                    if(res.status){
                                        $('.productSelectionDetail .tipsArea').show();
                                        $('.productSelectionDetail .tipsArea .addCartSuccess').show();
                                        setTimeout(() => {
                                            $('.productSelectionDetail .tipsArea .addCartSuccess').hide();
                                            $('.productSelectionDetail .tipsArea').hide();
                                        }, 3000);
                                    }
                                },
                                error:function(err){
                                    console.log('err',err);
                                }
                            })
                        }
                        else{
                            console.log('addCart 还有参数没选择');
                            var paramTips = '<div class="selectParams">';
                            paramTips += $('.productSelectionDetail .paramTips').html();
                            paramTips += '</div>'

                            // 移除原来的 添加新的
                            $('.productSelectionDetail .tipsArea .selectParams').remove();
                            $('.productSelectionDetail .tipsArea').append(paramTips);

                            // 展示 3000ms之后隐藏
                            $('.productSelectionDetail .tipsArea').show();
                            $('.productSelectionDetail .tipsArea .selectParams').show();
                            setTimeout(() => {
                                $('.productSelectionDetail .tipsArea .selectParams').hide();
                                $('.productSelectionDetail .tipsArea').hide();
                            }, 1500);

                        }
                    }
                },
                error:function(err){
                    console.log('err',err);
                }
            })


        })
    }
</script>
</html>